from TDhelper.web.utils.permission.server import regist_permission
from TDhelper.Event.webEvent.Events import Event
from TDhelper.generic.requier import R as require
from TDhelper.network.rpc.Client.service import SRC
from core.config import *
from core.service import *
from core.log import logging
import sys
# 反射获取类
def reflectClass(cls):
    return require(cls).getType()

# RPC 服务注册
def RegisterRpc(regist_type:int=0):
    logging.info("begin register rpc...")
    regist_instance= SRC(
        uris=str.split(cfg.RPC_CONFIG_URI), 
        server_cnf={
            "service": "api/services",
            "host": "api/hosts",
            "method": "api/uri",
            "params": "api/params",
            "return": "api/returns",
            "return_desc": "api/returnDescriptons"
        },
        rpc_conf_header={
            "name": cfg.SERVICE_NAME,
            "description": cfg.SERVICE_DESCRIPTION,
            "key": cfg.SERVICE_KEY,
            "secret": cfg.SERVICE_ACCESS_SECRET,
            "protocol": cfg.SERVICE_PROTOCOL,
            "hosts": [{
                    "host":item.split(":")[0],
                    "port":80 if len(item.split(":"))<2 else item.split(":")[1],
                    "siffer":"api/sniffer",
                    "proto":cfg.SERVICE_PROTOCOL
                } for item in str.split(cfg.SERVICE_HOST)]
            },
        logger= logging
        )
    if regist_type==0:
        regist_instance.AutoRegister(RPC_REGISTER_LIST)
    elif regist_type==1:
        #register by json config file.
        regist_instance.Register(
                os.path.join(
                    sys.path[0],
                    "config/regist_conf/rpc.json"
                ),
                filepath=True
        )
    else:
        logging.error('regist type error, 0(auto cls),1(by confgure file.)')
    logging.info("end register rpc...")
    
# 远程配置中心注册.

def RegisterConfig():
    # todo register config to remote.
    logging.info("开始注册远程配置参数...")
    try:
        ret= REMOTE_SERVICE.REMOTE_CONFIG.SERVICES_CREATE(**{"http_data_service_key": cfg.SERVICE_KEY, "http_data_name": cfg.SERVICE_NAME})
        if ret['state']==200:
            logging.info("远程配置中心服务注册成功.")
            logging.info("开始注册远程配置...")
            config_service_id = ret["msg"]["id"]
            CONFIGS = BASE_REMOTE_CONFIG
            for k, v in CONFIGS.items():
                ret = REMOTE_SERVICE.REMOTE_CONFIG.CONFIGS_CREATE(**{"http_data_config_key": k, "http_data_config_value": v, "http_data_service": config_service_id})
                if ret["state"] == 200:
                    logging.info('register remote config(%s) success.' % k)
                else:
                    logging.error("register remote config(%s) failed. %s" %
                                (k, ret["msg"]))
            logging.info("远程配置注册完成...")
        else:
            logging.error("register remote config center service failed. msg - %s." % ret["msg"])
    except Exception as e:
        logging.error(e.args)

# 事件注册
def RegisterEvent():
    EVENT_REGISTER = None
    if EVENT_CONFIG:
        if EVENT_CONFIG["state"]==200:
            EVENT_REGISTER = Event(EVENT_CONFIG['msg']['host'],
                                cfg.SERVICE_KEY,
                                EVENT_CONFIG['msg']["token"]
                                ) if EVENT_CONFIG['state'] == 200 else None
    if EVENT_REGISTER:
        logging.info("Begin register web event:")
        EVENT_REGISTER.AutoRegister(cfg.EVENT_CONF_PATH, EVENT_REGISTER)
        logging.info("END register web event.")
    else:
        logging.error("ERROR:EVENT_REGISTER is none.")
    
# 权限注册
def RegisterPermission():
    try:
        o= regist_permission(
                conf_path=register_permission_path,
                union_app=cfg.APP_ID,
                platform_key=cfg.SERVICE_KEY,
                domain="".join([cfg.SERVICE_PROTOCOL,cfg.SERVICE_HOST]),
                encode= cfg.CODING
            )
        o.set_handle(
                handle= REMOTE_SERVICE,
                service_key="PERMISSION_CENTER",
                method_key="PERMISSION_COLLECTS_ADD"
            )
        logging.info("Begin register permission:")
        o.register()
        logging.info("End register permission.")
    except Exception as e:
        logging.error(e.args)